<?php

namespace app\service;

use app\model\Nav;
use app\model\Route;
use app\model\Website;
use XMLWriter;

class Sitemap
{
    public $websiteId = null;
    public $sellerId = null;
    public $path = null;
    public $title = null;
    public $domain = null;
    protected $data = [];
    protected $xmlArray = [];
    protected $getFullUrl = [];

    public function __construct($sellerId, $websiteId)
    {
        $this->websiteId = $websiteId;
        $this->sellerId = $sellerId;
    }

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     */
    public function websiteInfo() {
        // 站点信息读取
        $website = new Website();
        $where = [
            'id' => $this->websiteId,
            'seller_id' => $this->sellerId,
            'status'=> 1,
        ];
        $res = $website->getWebsite($where);

            $this->title = $res['data']['title'];
            $this->domain = $res['data']['domain'];
    }

    public function scan() {

        $this->websiteInfo();
        // 站内域名扫描

        $routeWhere = [
            'website_id' => $this->websiteId,
            'seller_id' => $this->sellerId,
        ];
        $route = new Route();
        $this->getFullUrl =  $route->getFullUrl($routeWhere);

        foreach ($this->getFullUrl as $value) {
            $param = [
                'seller_id' => $this->sellerId,
                'website_id' => $this->websiteId,
                'loc' =>$this->domain.'/'.$value,
                'priority'=> '1.0',
                'changefreq' => 'weekly',
                'update_time' => date('Y-m-d H:i:s'),
            ];

            array_push($this->data, $param);
        }

    }

    protected function xmlRead() {
        // xml文件读取
        $path = './xml/'.$this->websiteId.'_sitemap.xml';
        try {
            $xmlFile = file_get_contents($path);
        } catch (\Exception $e) {
            $xmlFile = '';
        }
        $xmlObj = simplexml_load_string($xmlFile);
        $xmlJson = json_encode($xmlObj);
        $this->xmlArray = json_decode($xmlJson, true);

    }

    /**
     * @return string|null
     */
    public function siliamGen() {
        // 死链文件生成
        $name = $this->websiteId.'_silian';

        $this->xmlRead();

        $intersect = [];

        if (!empty($this->xmlArray) && !empty($this->getFullUrl)) {

            // 交集
            foreach ($this->getFullUrl as $new) {
                foreach ($this->xmlArray['url'] as $old) {
                    $url = $this->domain.'/'.$new;
                    if ($url == $old['loc']){
                        array_push($intersect, $url);
                        break;
                    }
                }
            }

            // 差集
            foreach ($intersect  as $meddle) {
                foreach ($this->xmlArray['url'] as $key=>$data) {
                    $res = strcmp($meddle, $data['loc']);
                    if ($res == 0) {
                        unset($this->xmlArray['url'][$key]);
                        break;
                    }
                }
            }

            $this->xmlWrite($name, $this->xmlArray['url']);

            $path = $this->domain.'/xml/'.$name.'.xml';
            return $path;
        } else {
            return null;
        }
    }

    /**
     * @return string
     */
    public function sitemapGen() {
        // sitemap文件生成
        $name = $this->websiteId.'_sitemap';

        $this->xmlWrite($name, $this->data);

        $path = $this->domain.'/xml/'.$name.'.xml';
        return $path;
    }

    public function xmlWrite($name, $data) {
        // xml文件生成
        header("Content-type: text/html; charset=utf-8");

        $xml = new XMLWriter();

//        $xml->openUri("php://output");	// 输出到网页控制台
        if ($name) {
            $path = "./xml/".$name.".xml";
            $xml->openUri($path);		// 输出到文件，需要读写权限，推荐 chmod 766 filename
        } else {
            $path = "./xml/sitemap.xml";
            $xml->openUri($path);
        }

        // 设置缩进字符串
        $xml->setIndentString("\t");
        $xml->setIndent(true);

        // xml文档开始
        $xml->startDocument('1.0', 'utf-8');

        // 创建根节点
        $xml->startElement("HuoCmsInfo");
        if ($data) {
            foreach ($data as $value) {
                $loc = !empty($value['loc']) ? $value['loc'] : '';
                $priority = !empty($value['priority']) ? $value['priority'] : '1.0';
                $lastmod = !empty($value['update_time']) ? $value['update_time'] : '';
                $changefreq = !empty($value['changefreq']) ? $value['changefreq'] : '';

                // 节点1
                $xml->startElement("url");
                $xml->startElement("loc");
                $xml->text($loc);
                $xml->endElement();

                $xml->startElement("priority");
                $xml->text($priority);
                $xml->endElement();

                $xml->startElement("lastmod");
                $xml->text($lastmod);
                $xml->endElement();

                $xml->startElement("changefreq");
                $xml->text($changefreq);
                $xml->endElement();
                $xml->endElement();
            }
        }
        $xml->endElement();
    }
}